<template>
  <div class="product-detail-container">
    <!-- 复用 HomePage 的头部导航 -->
    <div class="header">
      <div class="header-inner">
        <div class="logo">
          <router-link to="/home">
            <img src="@/assets/Logo.png" alt="鲸选Logo" />
          </router-link>
        </div>

        <!-- 搜索框 + 返回主页按钮 -->
        <div class="search-and-back">
          <div class="search-bar" @click.stop>
            <input v-model="searchQuery" type="text" placeholder="搜索商品" @keypress.enter="handleSearch" />
            <button @click="handleSearch">搜索</button>
          </div>
          <router-link to="/home" class="back-home-btn">返回主页</router-link>
        </div>

        <!-- 用户信息区域（带下拉菜单） -->
        <div class="user-info" @click.stop>
          <div class="user-avatar">
            <img :src="userAvatar" alt="用户" />
          </div>
          <div>
            <span class="username" @click="toggleDropdown">{{ displayName }}</span>
            <div v-show="isDropdownOpen" class="dropdown-menu">
              <div v-for="(item, index) in dropdownItems" :key="index" class="dropdown-item"
                @click="handleDropdownClick(item)">
                {{ item.text }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <p>正在加载商品详情...</p>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error-container">
      <h2>{{ error }}</h2>
      <router-link to="/home">返回首页</router-link>
    </div>

    <!-- 主体内容 -->
    <div v-else-if="product" class="main-content">
      <!-- 左侧：商品图片 -->
      <div class="product-image-section">
        <div class="image-placeholder">
          <img :src="product.imageUrl || product.img || 'https://via.placeholder.com/400x400?text=商品图片'" :alt="product.productName || product.title" />
        </div>
      </div>

      <!-- 右侧：商品信息 -->
      <div class="product-info-section">
        <h1 class="product-title">{{ product.productName || product.title }}</h1>
        <p v-if="product.subtitle" class="product-subtitle">{{ product.subtitle }}</p>
        <p class="product-price">¥{{ product.price }}</p>

        <div class="description-box">
          <h3>商品描述</h3>
          <p class="description-text">{{ product.description || '暂无描述' }}</p>
        </div>

        <div class="reviews-box">
          <h3>用户评价</h3>
          <div class="review-list">
            <div v-for="(review, index) in product.reviews" :key="index" class="review-item">
              {{ review }}
            </div>
            <div v-if="!product.reviews || product.reviews.length === 0" class="review-item">
              暂无评价
            </div>
          </div>
        </div>

        <!-- 复合按钮：左侧加入购物车，右侧跳转购买 -->
        <div class="dual-action-button">
          <button class="cart-part" @click="addToCart">
            <span>🛒</span> 加入购物车
          </button>
          <button class="buy-part" @click="goToBuy">
            立即购买
          </button>
        </div>
      </div>
    </div>

    <!-- 商品不存在 -->
    <div v-else class="not-found">
      <h2>商品未找到</h2>
      <router-link to="/home">返回首页</router-link>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getProductDetail, recordLinkClick } from '@/api'
import { useCartStore } from '@/stores/cart'
import { getVisitorId } from '@/utils/visitor'

const route = useRoute()
const router = useRouter()
const cartStore = useCartStore()
import { useUserStore } from '@/stores/user'
import { computed } from 'vue'

const userStore = useUserStore()
const defaultAvatar = new URL('@/assets/user-01.svg', import.meta.url).href
const userAvatar = computed(() => userStore.info?.icon || defaultAvatar)
const displayName = computed(() => userStore.userName || '未登录')
const product = ref(null)
const searchQuery = ref('')
const isDropdownOpen = ref(false)
const loading = ref(false)
const error = ref(null)

// ========== 用户下拉菜单 ==========
const dropdownItems = [
  { text: '购物车', to: '/shopping-cart' },
  { text: '个人中心', to: '/personalcenter' },
  { text: '切换账号', to: '/user-login' },
  { text: '修改密码', to: '/change-password' },
  { text: '退出登录', to: '/user-login' },
];

const toggleDropdown = () => {
  isDropdownOpen.value = !isDropdownOpen.value;
};

const handleDropdownClick = (item) => {
  isDropdownOpen.value = false;
  if (item.text === '退出登录') {
    if (confirm('确定要退出登录吗？')) {
      router.push(item.to);
    }
  } else {
    router.push(item.to);
  }
};

// ========== 搜索 ==========
const handleSearch = () => {
  if (searchQuery.value.trim()) {
    router.push({ path: '/search', query: { q: searchQuery.value.trim() } });
  }
};

// ========== 按钮逻辑 ==========
const addToCart = async () => {
  if (!product.value?.productId) {
    alert('商品信息缺失，无法加入购物车')
    return
  }

  const success = await cartStore.addItem(product.value.productId.toString(), 1)
  if (success) {
    alert(`已将【${product.value.productName || product.value.title}】加入购物车！`)
  } else if (cartStore.error) {
    alert(`加入购物车失败：${cartStore.error}`)
  } else {
    alert('加入购物车失败，请稍后重试')
  }
}

const goToBuy = async () => {
  const url = product.value?.productUrl || product.value?.link
  if (!url) {
    alert('暂未提供购买链接')
    return
  }
  
  // 记录链接跳转
  try {
    const visitorId = getVisitorId()
    await recordLinkClick({
      visitorId,
      productId: product.value?.productId?.toString() || '',
      linkUrl: url,
      platformId: product.value?.platformId || null
    })
  } catch (error) {
    console.debug('记录链接跳转失败:', error)
  }
  
  const targetUrl = /^https?:\/\//i.test(url) ? url : `https://${url}`
  window.open(targetUrl, '_blank', 'noopener=yes,noreferrer=yes')
}

// ========== 点击外部关闭下拉 ==========
const handleClickOutside = (e) => {
  if (!e.target.closest('.user-info')) {
    isDropdownOpen.value = false;
  }
};

// 加载商品详情
const loadProductDetail = async () => {
  const id = route.params.id;
  console.log('商品详情页 - 获取商品ID:', id, '类型:', typeof id);
  
  loading.value = true;
  error.value = null;
  
  try {
    const response = await getProductDetail(id);
    console.log('API获取商品详情成功:', response);
    
    // 后端返回的数据结构可能是 { code: 200, message: "success", data: ProductResponse }
    // 需要提取出实际的商品数据
    if (response && response.data) {
      product.value = response.data;
    } else if (response) {
      // 如果直接返回商品数据
      product.value = response;
    } else {
      throw new Error('获取商品数据失败');
    }
    
    // 确保商品数据有必要的字段
    if (product.value) {
      // 统一字段名，确保模板能正确显示
      if (!product.value.title && product.value.productName) {
        product.value.title = product.value.productName;
      }
      if (!product.value.img && product.value.imageUrl) {
        product.value.img = product.value.imageUrl;
      }
      if (!product.value.productUrl && product.value.link) {
        product.value.productUrl = product.value.link;
      }
    }
  } catch (err) {
    console.error('获取商品详情失败:', err);
    error.value = '商品未找到或加载失败';
    product.value = null;
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  loadProductDetail();
  document.addEventListener('click', handleClickOutside);
});

onBeforeUnmount(() => {
  document.removeEventListener('click', handleClickOutside);
});
</script>

<style scoped>
@import '@/CSS/ItemInfo.css';
</style>
